package repositories

import (
	"fmt"
	"gcopyright/models"
	"log"
)

func (r *RepositoriesSqlite) CreatFileInfoTable() {

	sql := r.sqlite
	sqlStmt := `
	create table fileInfo_table (author text , content text ,content_short text,hash text ,Timestamp text ,title text);
	`
	_, err := sql.Exec(sqlStmt)
	checkErr(err)
}

func (r *RepositoriesSqlite) InsertFileInfoTable(author, content, contentShort, hash, title string, time int64) {
	sql := r.sqlite
	stmt, err := sql.Prepare("INSERT INTO fileInfo_table(author, content , content_short,hash,Timestamp,title) values(?,?,?,?,?,?)")
	checkErr(err)
	res, err := stmt.Exec(author, content, contentShort, hash, time, title)
	checkErr(err)
	_, err = res.LastInsertId()
	checkErr(err)
}
func (r *RepositoriesSqlite) UploadHashFileInfoTable(h, t string) {
	sql := r.sqlite
	stmt, err := sql.Prepare("UPDATE fileInfo_table SET hash = ? WHERE Timestamp = ?")
	checkErr(err)
	result, err := stmt.Exec(h, t)
	affectNum, err := result.RowsAffected()
	checkErr(err)
	fmt.Println("update affect rows is ", affectNum)
}

func (r *RepositoriesSqlite) QuernFileInfoTable() []models.SelectFile {
	sql := r.sqlite
	rows, err := sql.Query("SELECT * FROM fileInfo_table ")
	checkErr(err)
	var fileInfo models.FileInfoTable
	var front models.SelectFile
	var arrayFront []models.SelectFile
	for rows.Next() {
		err = rows.Scan(
			&fileInfo.Author,
			&fileInfo.Content,
			&fileInfo.ContentShort,
			&fileInfo.Hash,
			&fileInfo.TimeStamp,
			&fileInfo.Title)
		front = models.SelectFile{
			Title:     fileInfo.Title,
			Timestamp: fileInfo.TimeStamp,
			Hash:      fileInfo.Hash,
		}

		if r.checkRepeat(front.Hash) {
			arrayFront = append(arrayFront, front)
		}
		checkErr(err)
	}
	return arrayFront
}

func (r *RepositoriesSqlite) QuernFileInfoTableAllElement(hash string) models.FileInfoTable {
	sql := r.sqlite

	rows, err := sql.Query("SELECT * FROM fileInfo_table WHERE hash = ?", hash)
	checkErr(err)
	var fileInfo models.FileInfoTable
	for rows.Next() {
		err = rows.Scan(
			&fileInfo.Author,
			&fileInfo.Content,
			&fileInfo.ContentShort,
			&fileInfo.Hash,
			&fileInfo.TimeStamp,
			&fileInfo.Title)
		checkErr(err)
	}
	return fileInfo
}
func (r *RepositoriesSqlite) DeleteFileInfoTable() {
	sql := r.sqlite
	sqlStmt := `
	DROP TABLE fileInfo_table;
	`
	_, err := sql.Exec(sqlStmt)
	checkErr(err)
}

func (r *RepositoriesSqlite) DeleteFileInfoTableElement(h string) {
	sql := r.sqlite
	stmt, err := sql.Prepare("DELETE  FROM fileInfo_table WHERE hash = ?")
	if err != nil {
		log.Fatal(err)
	}
	result, err := stmt.Exec(h)
	affectNum, err := result.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("delete affect rows is ", affectNum)
}
